package io.plus.client;

import io.plus.common.Constants;
import io.plus.common.packet.auth.HeartbeatRequestMessage;
import io.plus.common.packet.metadata.Command;
import io.plus.common.protocol.Decoder;
import io.plus.common.protocol.Encoder;
import io.plus.common.protocol.Packet;
import io.plus.engine.client.ClientHandler;
import io.plus.engine.pulse.*;
import io.plus.server.Status;

import java.nio.ByteBuffer;


public class ClientHandlerImpl implements Handler, ClientHandler {

    /**
     * 编码：把业务消息包编码为可以发送的ByteBuffer 总的消息结构：消息头 + 消息体 消息头结构： 4个字节，存储消息体的长度 消息体结构：
     * 对象的json串的byte[]
     */
    @Override
    public ByteBuffer encode(Configuration configuration, AsynchronousSocketChannelContext asynchronousSocketChannelContext, PacketMetadata packetMetadata) {

        Packet packet = (Packet) packetMetadata;
        return Encoder.encode(configuration, asynchronousSocketChannelContext, packet);
    }

    @Override
    public Packet decode(AsynchronousSocketChannelContext asynchronousSocketChannelContext, ByteBuffer byteBuffer, int limit, int position, int readableLength) throws DecodeException {
        Packet packet = Decoder.decode(asynchronousSocketChannelContext, byteBuffer);
        return packet;
    }

    @Override
    public void handler(AsynchronousSocketChannelContext asynchronousSocketChannelContext, PacketMetadata packetMetadata) throws Exception {
        Packet packet1 = (Packet) packetMetadata;
        byte[] body = packet1.getBody();
        if (body != null) {
            String str = new String(body, Constants.CHARSET);
            System.out.println("收到消息：" + str);
        }

        return;
    }


    /**
     * 此方法如果返回null，框架层面则不会发心跳；如果返回非null，框架层面会定时发本方法返回的消息包
     */
    @Override
    public PacketMetadata heartbeatPacket(AsynchronousSocketChannelContext asynchronousSocketChannelContext) {
        HeartbeatRequestMessage heartbeatRequestMessage = new HeartbeatRequestMessage("");
        Packet heartbeatPacket = new Packet(//
                Command.heartbeat_request,//
                Status.ok,
                heartbeatRequestMessage.toByte());//


        return heartbeatPacket;
    }
}
